package com.maxqaq.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;

import java.util.Random;

/**
 * 短信发送工具类
 */
public class SmsUtil {

    private static final String accessKeyId = "LTAI4Fy3GWhBHPxmVKmYuBp4";

    private static final String accessKeySecret = "IFzcmKjZCaNhe8xbljYvQy7WQFo8uY";

    /**
     * 使用AK&SK初始化账号Client
     * @return
     * @throws Exception
     */
    public static Client createClient() throws Exception{
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        //访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    public static void sendSms(String phoneNumber, String content) throws Exception {
        Client client = createClient();
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                //设置发送者的电话号码
                .setPhoneNumbers(phoneNumber)
                //签名
                .setSignName("阿杰通讯")
                //发送模板CODE
                .setTemplateCode("SMS_208965510")
                //发送验证码
                .setTemplateParam("{code: " + content + "}");
        //发送
        SendSmsResponse response = client.sendSms(sendSmsRequest);
        System.out.println("短信发送状态：" + response.getBody().message);
    }

    public static String createCode() {
        String[] arr = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"};
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            int nextInt = random.nextInt(arr.length);
            sb.append(arr[nextInt]);
        }
        return sb.toString();
    }
}
